﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace APJunktion.ATP.PacketConverter
{
    public class PacketConverter
    {

        #region Properties
        XDocument _xSchema; 
        #endregion

        #region Init
        public PacketConverter()
        {
            if (_xSchema == null)
            {
                try
                {
                    _xSchema = XDocument.Load("ATPPacketDef.xml");
                }
                catch
                {
                    throw new Exception("Unable to load ATP packet definition");
                }
            }
        } 
        #endregion

        #region Public Methods
        public XDocument ConvertToXML(string packet)
        {
            XDocument xPacket = new XDocument();
            xPacket.Add(new XElement("ATPPacketDefinition", string.Empty));

            if (!packet.StartsWith("?"))
            {
                throw new Exception("Unknown packet definition:" + packet);
            }


            var ATPPacketDefinitions = from ATPPacketDefinition in _xSchema.Descendants("ATPPacketDefinition").Elements()
                                       select ATPPacketDefinition;

            foreach (var ATPPacketDefinition in ATPPacketDefinitions)
            {
                try
                {
                    int Position = int.Parse(ATPPacketDefinition.Attribute("position").Value);
                    int Length = int.Parse(ATPPacketDefinition.Attribute("length").Value);
                    NoControlCharString _cleanpacket = new NoControlCharString(packet.Substring(Position - 1, Length));

                    xPacket.Root.Add(CreateNode(ATPPacketDefinition.Name.ToString(), _cleanpacket.ToString()));

                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

            return xPacket;

        } 
        #endregion

        #region Private Methods
        private XElement CreateNode(string _nodename, string _packet)
        {
            return new XElement(_nodename, _packet);

        } 
        #endregion

    }
}
